package cn.chinaunicom.sdsi.frm.sys.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import cn.chinaunicom.sdsi.frm.sys.entity.SysStaff;
import cn.chinaunicom.sdsi.frm.sys.entity.SysStaffOrg;
import cn.chinaunicom.sdsi.frm.sys.service.SysOrgService;
import cn.chinaunicom.sdsi.frm.sys.service.SysStaffOrgService;
import cn.chinaunicom.sdsi.frm.sys.service.SysStaffService;
import cn.chinaunicom.sdsi.frm.sys.service.SysStaffServiceForPolice;
import cn.chinaunicom.sdsi.gacx.sys.util.FrmUserUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@RestController
@RequestMapping("staffForPolice")
public class SysStaffControllerForPolice extends SysStaffController {
    @Autowired
    @Qualifier("sysOrgServiceImplWithDis")
    private SysOrgService sysOrgService;
    @Autowired
    private SysStaffServiceForPolice sysStaffServicenew;
    @Autowired
    private SysStaffService sysStaffService;
    @Autowired
    private SysStaffOrgService sysStaffOrgService;

    @Value("${UPLOAD_SAVE_FILE_PATH}")
    private String path;

    @Override
    @RequestMapping("/sysStaffMain")
    @RequiresPermissions("sys:staff:search")
    public ModelAndView sysStaffMain(ModelAndView mv) {
        String staffKind = getCurrentSysStaff().getStaffKind();
        if (FrmUserUtils.isSuperAdmin()) {
            staffKind = "4";
        }
        mv.addObject("staffKind", staffKind);
        JSONArray ja = sysOrgService.asyncinitSysOrgTree(getCurrentSysStaff().getOrgId());
        mv.addObject("treeRootArray", ja);
        mv.setViewName("frm/sys/sysStaffController/staffMain");
        return mv;
    }

    @Override
    @RequestMapping("/searchMap4Page")
    @RequiresPermissions("sys:staff:search")
    public Map<String, Object> searchMap4Page(SysStaff sysStaff, Integer start, Integer length) {
        return sysStaffServicenew.searchMap4Page(sysStaff, start, length);
    }

    /** 
    * @Title: saveSysStaff
    * @author: JBY
    * @date: 2017年5月18日下午4:44:42
    * @Description: TODO
    * @param sysStaff
    * @param request
    * @return String
    * @throws 
    */

    @RequestMapping("/saveStaff")
    @RequiresPermissions("sys:staff:add")
    public String saveSysStaff(SysStaff sysStaff, HttpServletRequest request) {
        sysStaff = this.doPicUpload(sysStaff, request);// 处理图片上传
        // 密码转码
        sysStaff.setPasswd(new Md5Hash(sysStaff.getPasswd(), sysStaff.getLoginName(), 2).toHex());
        JSONObject obj = sysStaffService.saveSysStaffWithRole(sysStaff);
        int id = (Integer) obj.get("staffId");

        // 添加岗位
        SysStaffOrg sso = new SysStaffOrg();
        if (!"1".equals(sysStaff.getStaffKind())) {
            sso.setDuty(sysStaff.getAttra());
        }
        sso.setStaffId(id);
        sso.setOrgId(sysStaff.getOrgId());
        // sso.setOrgType(orgType);
        sso.setStaffOrgStatus("1");
        sso.setStaffOrgType("F");// 岗位类型
        sysStaffOrgService.addStaffOrg(sso);
        // 如果是公安人员，添加人员关联关系
        if (sysStaff.getOfficerId() != null && "1".equals(sysStaff.getStaffKind())) {
            sysStaffServicenew.addStaffLink(sysStaff);
        }
        return "success";
    }

    /**
     * 更新人员及岗位信息
     */
    @ResponseBody
    @RequestMapping("/updateGacxStaff")
    @RequiresPermissions("sys:staff:update")
    public String updateSysStaff(SysStaff sysStaff, HttpServletRequest request) {
        sysStaff = this.doPicUpload(sysStaff, request);// 处理图片上传
        String passwd = String.valueOf(sysStaff.getPasswd()).trim();
        if (!"null".equals(passwd) && !"".equals(passwd)) {
            passwd = new Md5Hash(passwd, sysStaff.getLoginName(), 2).toHex();
            sysStaff.setPasswd(passwd);
        }
        int i = sysStaffService.updateSysStaff(sysStaff);
        if (i != 0) {
            if ("1".equals(sysStaff.getStaffKind())) {
            	//查看关联表中是否有警员警官关联记录
            	int ii = sysStaffServicenew.selectStaffLink(sysStaff.getStaffId());
            	if(ii == 0){
            		//如果没有关联记录，则添加
            		sysStaffServicenew.addStaffLink(sysStaff);
            	}else{
            		//如果有关联记录，则修改 警员-警官 关联表
                    sysStaffServicenew.updateStaffLink(sysStaff);
            	}
                
            }
            // 修改人员-组织关联表
            sysStaffServicenew.updateStaffOrg(sysStaff);
            return "success";
        }

        return "faild";
    }

    @RequestMapping("getPhoto")
    public void getPhoto(@RequestParam("staffId") String staffId, HttpServletRequest request,
            HttpServletResponse response) {
        String fileName = "";
        File file = null;
        if (StringUtils.isEmpty(staffId)) {
            file = new File(
                    request.getSession().getServletContext().getRealPath("/") + "resource/images/default33333.png");
        } else {
            SysStaff staff = this.sysStaffService.selectStaffById(Integer.valueOf(staffId));
            if (staff.getStaffPic() == null) {
                file = new File(request.getSession().getServletContext().getRealPath("/")
                        + "resource/images/default33333.jpg");
            } else {
                fileName = path + File.separator + staff.getStaffPic();
                file = new File(fileName);
            }
        }
        FileInputStream inputStream = null;
        try {
            // 判断文件是否存在如果不存在就返回默认图标
            if (!(file.exists() && file.canRead())) {
                file = new File(
                        request.getSession().getServletContext().getRealPath("/") + "resource/images/loginuser.png");
            }
            inputStream = new FileInputStream(file);
            OutputStream stream = response.getOutputStream();
            byte[] b = new byte[inputStream.available()];
            inputStream.read(b);
            stream.write(b);
            stream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private SysStaff doPicUpload(SysStaff sysStaff, HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> uploadFiles = multipartRequest.getFiles("policeFile");
        if (uploadFiles.size() > 0) {
            String separator = File.separator;
            String fileName = UUID.randomUUID().toString() + "_" + uploadFiles.get(0).getOriginalFilename();
            String filePath = "policePhoto";// + separator + fileName;
            // 使用UUID为文件生成一个唯一编码
            String realPath = path + separator + filePath + separator + fileName;
            File pathFile = new File(path + separator + filePath);
            // 判断保存路径是否存在
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            try {
                uploadFiles.get(0).transferTo(new File(realPath));
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            sysStaff.setStaffPic(separator + filePath + separator + fileName);
        }
        return sysStaff;
    }
}
